<template>
	<div class="p-6">
		<el-card v-if="product">
			<el-row :gutter="20">
				<el-col :span="10">
					<img :src="product.image" class="w-full h-64 object-cover rounded" />
				</el-col>
				<el-col :span="14">
					<h2 class="text-xl font-bold mb-2">{{ product.name }}</h2>
					<p class="text-gray-500">分类：{{ product.category }}</p>
					<p class="text-lg text-red-500 font-medium mt-2">价格：¥{{ product.price }}</p>
					<p class="text-sm text-gray-700">库存：{{ product.stock }} 件</p>
					<el-input-number v-model="buyQuantity" :min="1" :max="product.stock" class="mt-2" />
					<div class="text-sm mt-1">总价：<span class="text-red-500 font-medium">¥{{ totalPrice }}</span></div>
					<div class="flex gap-4 mt-4">
						<el-button type="primary" size="large" @click="addToCart">加入购物车</el-button>
						<el-button type="warning" size="large" @click="addToFavorites">
							<el-icon class="mr-1">
								<Star />
							</el-icon> 收藏
						</el-button>
						<el-button type="success" size="large" @click="buyNow">立即购买</el-button>
					</div>
				</el-col>
			</el-row>
		</el-card>
		<div v-else>
			<el-empty description="未找到该商品" />
		</div>

		<el-dialog v-model="showPaymentDialog" title="模拟支付" width="400px">
			<p>您正在购买：</p>
			<p class="font-medium mt-1">{{ product?.name }}</p>
			<p class="text-red-500 mt-1">数量：{{ buyQuantity }}，总价：¥{{ totalPrice }}</p>
			<div class="text-center mt-4">
				<el-button type="primary" @click="confirmPayment">确认支付</el-button>
				<el-button @click="showPaymentDialog = false">取消</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Star } from '@element-plus/icons-vue'

const route = useRoute()
const productId = Number(route.params.id)

const imageModules = import.meta.glob('../../assets/images/*.jpg', { eager: true })

const categories = [
	{ name: '光刻材料', items: ['EUV光刻胶', 'G线光刻胶', '紫外宽谱光刻胶', '电子光束刻胶'] },
	{ name: '抛光材料', items: ['氧化硅抛光液', '氧化铝抛光液', '纳米抛光液'] },
	{ name: '工艺化学品', items: ['显影液', '去胶剂', '清洗剂', '蚀刻液'] }
]

const allProducts = []
let id = 1
categories.forEach(cat => {
	cat.items.forEach(sub => {
		const imgKey = `../../assets/images/${id}.jpg`
		const imagePath = imageModules[imgKey]?.default || ''
		allProducts.push({
			id: id++,
			name: `${sub} - ${cat.name}`,
			category: cat.name,
			price: (Math.random() * 500 + 100).toFixed(2),
			stock: Math.floor(Math.random() * 50 + 1),
			image: imagePath
		})
	})
})

const product = ref(allProducts.find(p => p.id === productId))
const showPaymentDialog = ref(false)
const buyQuantity = ref(1)

const totalPrice = computed(() => {
	return (buyQuantity.value * parseFloat(product.value.price)).toFixed(2)
})

const addToCart = () => {
	const cart = JSON.parse(localStorage.getItem('cart') || '[]')
	cart.push({ ...product.value, quantity: buyQuantity.value })
	localStorage.setItem('cart', JSON.stringify(cart))
	ElMessage.success('已加入购物车')
}

const addToFavorites = () => {
	const favs = JSON.parse(localStorage.getItem('favorites') || '[]')
	if (!favs.find(f => f.id === product.value.id)) {
		favs.push(product.value)
		localStorage.setItem('favorites', JSON.stringify(favs))
		ElMessage.success('已收藏')
	} else {
		ElMessage.warning('已在收藏夹中')
	}
}

const buyNow = () => {
	if (buyQuantity.value > product.value.stock) {
		ElMessage.warning('购买数量不能超过库存')
		return
	}
	showPaymentDialog.value = true
}

const confirmPayment = () => {
	if (buyQuantity.value > product.value.stock) {
		ElMessage.error('库存不足')
		return
	}
	product.value.stock -= buyQuantity.value
	showPaymentDialog.value = false
	ElMessage.success('支付成功！订单已生成')

	const orders = JSON.parse(localStorage.getItem('orders') || '[]')
	orders.push({
		id: Date.now(),
		productId: product.value.id,
		name: product.value.name,
		quantity: buyQuantity.value,
		total: totalPrice.value,
		time: new Date().toLocaleString()
	})
	localStorage.setItem('orders', JSON.stringify(orders))
}
</script>

<style scoped>
.text-xl {
	font-size: 1.25rem;
}
</style>
  
